package cn.itcast.n8;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

import static cn.itcast.n2.util.Sleeper.sleep;

@Slf4j(topic = "c.TestAqs")
public class TestAqs {
    public static void main(String[] args) {
        MyLock lock = new MyLock();
        new Thread(() -> {
            lock.lock();
            try {
                log.debug("locking...");
                sleep(3);
            } finally {
                log.debug("unlocking...");
                lock.unlock();
            }
        }, "t1").start();

        new Thread(() -> {
            lock.lock();
            try {
                log.debug("locking...");
            } finally {
                log.debug("unlocking...");
                lock.unlock();
            }
        }, "t2").start();
    }
}

// 自定义锁（不可重入锁）
class MyLock implements Lock {

    //独占锁
    class MySync extends AbstractQueuedSynchronizer {
        //尝试获取锁,
        @Override
        protected boolean tryAcquire(int arg) {
            //成功设置state
            if (compareAndSetState(0, 1)) {
                //设置owner为当前线程
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        @Override
        protected boolean tryRelease(int arg) {
            //设置owner为null
            setExclusiveOwnerThread(null);
            setState(0);//后面会加写屏障
            return true;
        }

        //是否持有独占锁?
        @Override
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }

        public Condition newCondition() {
            return new ConditionObject();
        }
    }


    private MySync sync = new MySync();

    //加锁（不成功就会进入等待队列等待）
    @Override
    public void lock() {
        sync.acquire(1); //会先调用tryAcquire，如果不成功，则进入等待队列
    }

    //加锁-可打断
    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);

    }

    //尝试加锁-只尝试一次
    @Override
    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    //尝试加锁-可以等待指定时间
    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(time));
    }

    //解锁
    @Override
    public void unlock() {
        sync.release(1); //release会调用tryRelease，再唤醒等待的线程

    }

    //创建条件变量
    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }
}